﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Newbe.TestDirector.Notification.Web.Domain.Impl
{
    internal class AppDataFolderHistoryTestDirectorDatabaseStore : IHistoryTestDirectorDatabaseStore
    {
        private static string StoreFolder
        {
            get
            {
                var dir = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(),
                    "TdAccessDatabases");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                return dir;
            }
        }

        void IHistoryTestDirectorDatabaseStore.AddNew(TestDirectorAcceessDb testDirectorAcceessDb)
        {
            File.Copy(testDirectorAcceessDb.FilePath,
                Path.Combine(StoreFolder, $"{testDirectorAcceessDb.TimeStamp:yyyyMMddHHmmss}.mdb"), true);
        }

        IEnumerable<TestDirectorAcceessDb> IHistoryTestDirectorDatabaseStore.GeTestDirectorAcceessDbs()
        {
            return GetAll();
        }

        private static IEnumerable<TestDirectorAcceessDb> GetAll()
        {
            return Directory.GetFiles(StoreFolder, "*.mdb").Select(x => new TestDirectorAcceessDb
            {
                FilePath = x,
                TimeStamp = DateTimeOffset.ParseExact(Path.GetFileNameWithoutExtension(x), "yyyyMMddHHmmss", null)
            }).ToArray();
        }

        TestDirectorAcceessDb IHistoryTestDirectorDatabaseStore.GetLastest()
        {
            return GetAll().OrderByDescending(x => x.TimeStamp).FirstOrDefault();
        }

        void IHistoryTestDirectorDatabaseStore.RemoveLastest()
        {
            var re = GetAll().OrderByDescending(x => x.TimeStamp).FirstOrDefault();
            if (re == null)
            {
                return;
            }
            File.Delete(re.FilePath);
        }
    }
}
